package org.apache.servicecomb.fence.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.ws.rs.QueryParam;

@RestController
@RequestMapping("/v1/scb/admin/discovery")
public class AdminController {

  @Autowired
  private DiscoveryClient discoveryClient;

  @Autowired
  private Environment environment;

  @GetMapping(path = "findServices")
  public FindServicesResponse findServices() {
    List<String> services = discoveryClient.getServices();
    FindServicesResponse response = new FindServicesResponse();
    response.setServices(services);
    response.setEnvironment(environment.getProperty("spring.cloud.servicecomb.service.application"));
    response.setApplication(environment.getProperty("spring.cloud.servicecomb.service.environment"));
    return response;
  }

  @GetMapping(path = "findServiceInstances")
  public FindServiceInstancesResponse findServiceInstances(@QueryParam("serviceName") String serviceName) {

    FindServiceInstancesResponse response = new FindServiceInstancesResponse();
    response.setInstances(discoveryClient.getInstances(serviceName));
    return response;
  }
}
